﻿namespace HuwmanCode

open System
open System.Runtime.CompilerServices

[<AutoOpen>]
[<Extension>]
[<RequireQualifiedAccess>]
module Action =
    /// <summary>
    /// Invokes an action with exception handling and invokes a compensation action should an exception occur.
    /// </summary>
    /// <param name="compensate">The action to invoke should an exception occur.</param>
    /// <param name="action">The action to invoke.</param>
    /// <return>Option.Some if no exception occurs, otherwise Option.None</return>
    [<Extension>]
    let Try (compensate:exn Action) (action: Action) =
        try
            action.Invoke()
            Some()
        with e ->
            if compensate <> null then compensate.Invoke e 
            None

    /// <summary>
    /// Invokes an action with exception handling and invokes a compensation action should an exception occur.
    /// </summary>
    /// <param name="compensate">The action to invoke should an exception occur.</param>
    /// <param name="action">The action to invoke.</param>
    /// <return></return>
    [<Extension>]
    let TryWithRethrow (compensate:exn Action) (action:Action) =
        try
            action.Invoke()
        with e -> 
            if compensate <> null then compensate.Invoke e
            reraise()